<?php
 use Think\Cache;
 use Lib\PasswordHash;
 use Think\Image;
 
 	/**
	* 密码加密
	*/
	function _enPasswd($passwd){
		 $ph = new PasswordHash();
		 
		 return $ph->HashPassword($passwd);
	}	
    /**
     * 检测密码是否正确
     * @param $getPwd
     * @param $dataPasswd
     */
    function _checkPwd($getPwd,$dataPasswd)
    {
        $ph = new PasswordHash();
		
        if($ph->CheckPassword($getPwd,$dataPasswd))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
	/*
	 *删除数据 缓存$cache
	 *%d - double,包含正负号的十进制数（负数、0、正数）
	 *%s - string,字符串
	 *%f - float,浮点数
	 *$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();
	 */
	function _getDel($table,$where,$data='',$cache){
		
		error_dump();
		//删除缓存
		S($cache,null);	
		
		if (is_array($where) && !$data) {
			$result = M($table)->where($where)->delete();
		} else {
			$result = M($table)->where($where,$data)->delete();
		}				
		return $result ;				 
	 }
	 
	/*
	 *修改数据
	 *%d - double,包含正负号的十进制数（负数、0、正数）
	 *%s - string,字符串
	 *%f - float,浮点数
	 *
	 */
	function _getEdit($table,$where,$data2,$data,$cache){
		
		error_dump();	
		//删除缓存
		S($cache,null);
		
		if (is_array($where)) {
			$result = M($table)->data($data)->where($where)->save();	
		} else {
			$result = M($table)->data($data)->where($where,$data2)->save();
		}		
		return $result ;					 
	 }
	 
	/*
	 *添加数据
	 *%d - double,包含正负号的十进制数（负数、0、正数）
	 *%s - string,字符串
	 *%f - float,浮点数
	 *
	 */
	function _getAdd($table,$data,$cache){
		
		error_dump();	
		//删除缓存
		if ($cache) {
			S($cache,null);	
		}		
		$result = M($table)->add($data);
		return $result ;					 
	 }
	 
	/*
	 *列表查询
	 *%d - double,包含正负号的十进制数（负数、0、正数）
	 *%s - string,字符串
	 *%f - float,浮点数
	 *
	 */
	function _getList($table,$where,$data='',$cache,$order,$peg,$num,$field='*'){

		error_dump();
		if ($cache) {
			// 获取缓存数据  
			$list = S($cache);
		}

		if (!$order) {
			$order = '';
		}
		if (!$peg) {
			$peg = 1;
		}
		if (!$num) {
			$num = 1000;
		}
		//dump($list);die;
		// 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取		

		if (!$list) {
			if (is_array($where)) {
				$list = M($table)->where($where)->field($field)->order($order)->page($peg.','.$num)->select();
			} else {
				$list = M($table)->where($where,$data)->field($field)->order($order)->page($peg.','.$num)->select();
			}
			if ($cache) {
				S($cache,$list);				
			}
		}
		
		return $list ;					 
	 }
	 
	/*
	 *关联查询
	 *%d - double,包含正负号的十进制数（负数、0、正数）
	 *%s - string,字符串
	 *%f - float,浮点数
	 *
	 */
	function _getJoinOne($table,$join,$where,$data='',$cache,$field='*'){
		
		error_dump();		

		if ($cache) {
			// 获取缓存数据  
			$list = S($cache);
		}	
		// 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取		
		if (!$list) {
			if (is_array($where)) {
				$list = M($table)->join($join)->where($where)->field($field)->find();
			} else {
				$list = M($table)->join($join)->where($where,$data)->field($field)->find();
			}
			if ($cache) {
				S($cache,$list);	
			}						
		}				
		return $list;
	 }
	 
	 
	/*
	*随机hash
	*/	
    function shopHash($SuijiHash,$hash){
		
		if ($_SESSION[$SuijiHash]==$hash) {
			return false;
		} elseif (!$_SESSION[$SuijiHash]) {
			session($SuijiHash,$hash);
			return true;
		} else {
			session($SuijiHash,$hash);
			return true;			
		}
    }
	 
	/*
	*上传图片
	*/
	 function upload($store=0){	
	  
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg', 'bmp');// 设置附件上传类型
		if ($store) {
			 $upload->rootPath  =     './Public/upload/store/'; // 设置附件上传根目录
			 $src = '/Public/upload/store/';
			 $upload->savePath = $_SESSION['user_id'].'/'	; // 设置附件上传（子）目录
		} else {
			$upload->rootPath  =     './Public/upload/image/'; 
			$src = '/Public/upload/image/';
			$upload->savePath = '' ;
		}	
		// 上传文件 
		$info   =   $upload->upload($_FILES);
		foreach($info as $file){   
			if (count($info)<2) {
				$info = $src.$file['savepath'].$file['savename']; 
			} else {
				$info[$file['key']] = $src.$file['savepath'].$file['savename']; 
			}    		   
		}	
		if (!$info) {
			// 上传错误提示错误信息
			$upload->getError();
		} else {		
			$_SESSION['PicH']=$info;
			unset($info);		
			// 上传成功
			return $_SESSION['PicH'];
		}
	}

    /**
     * 
     * @param type $code 省份、市、区（县）对应的代码
     */
    function code_area($cache){
		
		if ($cache) {
			// 获取缓存数据  
			$area = S($cache);
		}		
		if (!$area) {
			$area = M("area")->where('area_id<=35')->select();
			if ($cache) {
				S($cache,$area);	
			}						
		}		
       return $area;
    }

    /**
     * 
     * @param type $code 省份、市、区（县）对应的代码
     */
    function code_area_son($str,$id){
       $area = M("area")->where(array($str=>$id))->select();
	  // $arr[]['area_name']=$area[0]['area_name'];	
       return $area;
    }
	
    /**
     * 
     *商品分类子级分类
     */
    function goods_class_son($str,$id){
       $list = M("goods_class")->where(array($str=>$id))->select();
       return $list;
    }
	
	/*
	*字符串处理
	*/	
    function strColation($str){
		$str = json_encode($str);
		$str = addslashes($str);	
		return $str ;
    }	

	/*
	*字符串解析
	*/	
    function strAnalysis($str){
		$str = stripslashes($str);
		$str = json_decode($str);
		foreach ($str as $k=>$v) {
			if (is_object($v)) {
				$str [$k] = (array) $v;
			}
		}
		return $str ;		
    }	
 
	/*
	 *清除所有S缓存
	 *
	 */
	function SClear(){
		$cache = Cache::getInstance();  
		$cache ->clear() ;		
	 }		
	/*
	 *清除所有缓存
	 *
	 */	
	function AllClear(){
		
		$cache = Cache::getInstance();  
		$cache ->clear() ;
		del_cache() ;	
		
	 }

	/*
	 *清除所有缓存
	 *
	 */
	function NetClear(){
		del_cache() ;		
	 }		 	 
	 
	/*
	*获取要清除的目录和目录所在的绝对路径
	*
	*/	
	function del_cache(){
		//得到文件的绝对路径
		$abs_dir=dirname(dirname(dirname(dirname(__FILE__))));
		$pa=$abs_dir.'/Bobo/Runtime/';	
		$file=scandir($pa);
		
		@mkdir($file,0777,true);

			for ($i=0;$i<=count($file);$i++) {
				if($file[$i]!="." && $file[$i]!="..") {
					$flie_arr[$i] = $file[$i];
					$del_f = $pa.$flie_arr[$i];
					if (file_exists($del_f)) {
					 $elll = $del_f;	
					 $del = cache_deldir($elll);					 			 
					}						
				}				
			}					
	}
	
	/*
	*
	*删除执行的方法
	*/
	function cache_deldir($dir) {
	  //先删除目录下的文件：
	  $dh=opendir($dir);
	  while ($file=readdir($dh)) {
		if($file!="." && $file!="..") {
		  $fullpath=$dir."/".$file;
		  if(!is_dir($fullpath)) {
			  unlink($fullpath);
		  } else {
			  cache_deldir($fullpath);
		  }
		}
	  }
	  closedir($dh);
	  //删除当前文件夹：
	  if(rmdir($dir)) {
		return true;
	  } else {
		return false;
	  }
	}	

	/*
	*会员后台调用
	*
	*会员信息所有的session 添加
	*/
	function userInfo_cache($uid,$info,$type=0) {

		unset($u_info);
		unset($data);
		$u_info ['ch_user_id'] = $uid ;
		$u_info ['ch_name'] = $info ;
		$u_info ['ch_ip'] = get_client_ip() ;
		$u_info ['ch_addtime'] = time() ;
		$u_info ['ch_number'] = 1 ;
		$cache = 'uInfo_cache'.$uid.$info;
		
		$getOne = userInfo_get($uid,$info) ;
		
		if ($getOne) {
				
			//添加
			if ($type) {
				//判断是否已添加一次
				if ($getOne['ch_user_id'] == $u_info['ch_user_id'] && $getOne['ch_name']== $u_info['ch_name']) {
					$u_info ['ch_number'] = $getOne ['ch_number'] + 1 ;
					$data ['ch_number'] = $getOne ['ch_number'] + 1 ;
				}					
			}				
		}		
			//return $data ['ch_number'] ;
		if ($type==1 && $getOne) {
			$where = "ch_user_id=%d and ch_name='%s'" ;
			$arr = array($u_info['ch_user_id'],$u_info ['ch_name']) ;
			$result = M('userinfo_cache')->data($data)->where($where,$arr)->save() ;
		} else if ($type==2) {
			$result = M('userinfo_cache')->add($u_info) ;
			//非法操作则强制退出
			if (!$result) {
				session(null);
			}
		}
		
		//删除缓存
		S($cache,null) ;
		//更新缓存	
		userInfo_get($uid,$info) ;		
		return $result;		
	}
	
	/*
	*会员前台调用
	*
	*会员信息所有的session 1条查询 
	*/
	function userInfo_find($uid,$info) {
		
		$number = 0 ;
		unset($data);
		$data ['ch_user_id'] = $uid ;
		$data ['ch_name'] = $info ;
		$data ['ch_ip'] = get_client_ip() ;
		$data ['ch_addtime'] = time() ;
		$data ['ch_number'] = 1 ;
		
		$cache = 'uInfo_cache'.$uid.$info;
		
		$getOne = userInfo_get($uid,$info) ;
		
		//dump($getOne);die;
		if ($getOne) {

			//判断是否已添加一次
			if ($getOne['ch_user_id'] == $data['ch_user_id'] && $getOne['ch_name']== $data['ch_name']) {				
				$list = $getOne  ;
			}					
		} else {
			//添加
			$result = userInfo_cache($uid,$info,2);
		}
		
		if ($list['ch_number']>1) {
			
			session($info,null) ;
			
			$where = "ch_user_id=%d and ch_name='%s' " ;
			$arr = array($data['ch_user_id'],$data ['ch_name']) ;
			$u_info ['ch_number'] = 1;
			$result = M('userinfo_cache')->data($u_info)->where($where,$arr)->save() ;
			unset($where) ;
			unset($arr) ;
		}			
	}
	
	/*
	*
	*会员信息所有的session 所有查询
	*/
	function userInfo_get($uid,$info) {
		//删除缓存
		if ($uid) {
			$cache = 'uInfo_cache'.$uid.$info;
			
			if (S($cache)) {
				$list = S($cache) ;	
			} else {
				$field = 'ch_user_id,ch_name,ch_ip,ch_addtime,ch_number' ;
				$where = "ch_user_id=%d and ch_name='%s'" ;
				$data = array($uid,$info) ;
				$list = M('userinfo_cache')->where($where,$data)->field($field)->find();
				S($cache,$list) ;
			}
			//dump(S('uInfo_cache'.$uid));die;			
		}
		return $list ;	
		
	}	
	
	/*
	*
	*会员信息所有的session 退出登录删除
	*/
	function userInfo_del() {
		//删除session
		$cache = 'uInfo_cache'.$_SESSION['user_id'].'st_joinin_data';
		S($cache,null) ;
		unset($cache);
		$cache = 'uInfo_cache'.$_SESSION['user_id'].'shop_store';
		S($cache,null) ;	
		$where = "ch_user_id=%d and ch_ip='%s'" ;
		$arr = array($_SESSION['user_id'],get_client_ip()) ;	
		M('userinfo_cache')->where($where,$arr)->delete();	
	}
	  
	/*
	 *退出登录清除缓存
	 *$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();
	 */
	function outClear(){
		 userInfo_del() ;
		 $cache = 'store_class'.$_SESSION['user_id'] ;		
		 S($cache,null) ;
		 unset($cache);
 		 $cache = 'store_joinin'.$_SESSION['user_id'] ;		
		 S($cache,null) ;
		 unset($cache);
		 $cache = 'user_'.$_SESSION['user_id'] ;		
		 S($cache,null) ;
		 unset($cache);
		 $cache = 'store_data'.$_SESSION['user_id'] ;		
		 S($cache,null) ;
		 unset($cache);
/* 		 $cache = 'st_grade_data' ;//退出登录不需要清除	
		 S($cache,null) ;
		 unset($cache);
		 $cache = 'service_info' ;//退出登录不需要清除		
		 S($cache,null) ;
		 unset($cache);
		 $cache = 'province' ;	//退出登录不需要清除	 */	 
		 S($cache,null) ;
		 unset($cache);		 
		 $cache = 'img_dir'.$_SESSION['user_id'];
		 S($cache,null);
		 $ip = get_client_ip() ;
		 unset($cache);
		 for ($i=1;$i<=30;$i++) {
			 $cache = 'store'.$i ;
			 S($cache) && S($cache,null);
			 unset($cache);
			 $cache = 'myuser'.$i ;
			S($cache) && S($cache,null);
			 unset($cache);
			 $cache = 'store_'.$i ;
			 S($cache) && S($cache,null);
			 unset($cache);
/* 			 $cache = 'store_list'.$i.$ip ;
			 S($cache) && S($cache,null);
			 unset($cache);*/
			 $cache = 'store_page'.$i.$ip ; 
			 S($cache) && S($cache,null);
			 unset($cache);
			 $cache = 'goods_list'.$i.'_'.$_SESSION['user_id'] ;
			 S($cache) && S($cache,null);
			 unset($cache);
			 $cache = 'depot_list'.$i.'_'.$_SESSION['user_id'] ;
			 S($cache) && S($cache,null);
			 unset($cache);
		 }
		 
		 $cache = 'img_dir'.$_SESSION['user_id'] ;		
		 S($cache,null) ;
		 unset($cache);	 
	 }
	 
	/*
	*
	*一对多查询
	*/	
	function _RowsJoin($table,$join,$where,$data,$field='*',$order='',$peg,$num,$group='',$cache) {
		
		if ($cache) {
			// 获取缓存数据  
			$list = S($cache);
		}
		//dump($list);die;

		if (!$peg) {
			$peg = 1;
		}
		
		$join1 = $join['join1'] ;
		$join['join2'] && $join2 = $join['join2'] ;
		$join['join3'] && $join3 = $join['join3'] ;
		$join['join4'] && $join4 = $join['join4'] ;
		$join['join5'] && $join5 = $join['join5'] ;
		
		if (!$list) {
			$list = M()->field($field)->table($table)->join($join1)->join($join2)->join($join3)->join($join4)->join($join5)->where($where,$data)->group($group)->order($order)->page($peg.','.$num)->select();
			if ($cache) {
				S($cache,$list);	
			}			
		}		
		return $list ;
	}

	/*
	 *关联查询
	 *%d - double,包含正负号的十进制数（负数、0、正数）
	 *%s - string,字符串
	 *%f - float,浮点数
	 *$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();
	 */
	function _getJoinList($table,$join,$where,$data='',$cache,$order,$peg,$num,$field=''){
		
		error_dump();		
		
		if ($cache) {
			// 获取缓存数据  
			$list = S($cache);
		}
		if (!$order) {
			$order = '';
		}
		if (!$peg) {
			$peg = 1;
		}		
		// 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取		
		if (!$list) {
			if (is_array($where)) {
				$list = M($table)->join($join)->where($where)->field($field)->order($order)->page($peg.','.$num)->select();
			} else {
				$list = M($table)->join($join)->where($where,$data)->field($field)->order($order)->page($peg.','.$num)->select();
			}
			if ($cache) {
				S($cache,$list);	
			}						
		}				
		return $list;
	 }
	 
	/*
	*URL 加密
	*
	*/		
	function hashUrl($url) {
	}
		
	/*
	*URL 解密
	*
	*/		
	function decUrl() {
		
	}	
		
	/** 
	 * author:10xjzheng
	 * Excel导入
	 * @param url 要生成的二维码的链接
	 * @param flag 是否生成图片保存起来，1是，0否（只是动态生成）
	 */
	function createQRcode($url,$flag=0){ 
	
		$host = $_SERVER["HTTP_HOST"];
		vendor("phpqrcode.phpqrcode");
				
		// 纠错级别：L、M、Q、H
		$level = 'L';
		// 点的大小：1到10,用于手机端4就可以了
		$size = 4;
		// 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
		if($flag){
			$path = "Public/QRcode/";
			if(!file_exists($path)){ 
				mkdir($path, 0700); 
			}
			// 生成的文件名
			$fileName = $path.time().'.png';
			QRcode::png($url, $fileName, $level, $size); 
			return $fileName;
		}else{
			// 生成的文件名  
			ob_end_clean();//清空缓冲区 
			QRcode::png($url, false, $level, $size);			
		}		
	}	

    //生成编号
    function number($zm,$id,$num=16)
    {

        $number=$zm.str_pad($id,$num,"0",STR_PAD_LEFT);
        return $number;
    }

	
	/**
	 * 删除购物车
	 *
	 * @param array $buy_items 商品ID => 购买数量
	 */
	 function delCart($goods_id) {
		  $cart = strAnalysis(session('_cart')) ;
		  foreach ($cart as $key => $v) {
			 if ($v['goods_id']==$goods_id) {
				 $del_num = $v['goods_num'] ;						
				 unset($v);
			 } else {
				 $amount += $v['amount'] ;
				 $cart_list [] = $v ;
			 }						
		 }
		 session('_cart',strColation($cart_list)) ;
		 $num = session('_cart_goods_num') -  $del_num;
		 if ($num<0) {
			 $num = 0 ;
		 }
		 session('_cart_goods_num',$num) ;
		 session('_cart_goods_amount',$amount) ;			
	 }	 

	/**
	 * 购物车产品信息
	 *
	 * @param array $buy_items 商品ID => 购买数量
	 */
	 function goodsCart($c_list, $c_arr) {
		 
			$str = $c_list ;
			$arr = explode(',',$c_arr);
			$table = '__SHOP_CART__ AS c' ;
			$order = 'st.store_id desc' ;
			$join['join1'] = 'INNER JOIN __PRODUCT__ AS g ON g.id=c.goods_id' ;
			$join['join2'] = 'LEFT JOIN __STORE__ AS st ON st.store_id=c.store_id' ;
			$field = 'c.*,g.price,g.goods_state,g.goods_verify,g.goods_marketprice,g.goods_freight,g.goods_storage,g.number,g.shop_area_ids,st.store_name,st.store_state,st.store_id,g.coin_num,g.give_coin,g.point_num' ;	
			$cart_list = _RowsJoin($table, $join, $str, $arr, $field, $order) ;
		
			if (!$cart_list) {					
				return false;
			}
			$st_id = '' ;
			$i = 0 ;
			
			foreach ($cart_list as $key=>$v) {
				
				//商品所在店铺
				if (!$storeid) {
					$storeid = $v["store_id"] ;
				}	
				//分区
				$cart_list [$key]['amount'] = $v['goods_num'] * $v['goods_price'];
				//支付总积分				
				$cart_list [$key]['amount_points'] = $v['goods_num'] * $v['point_num'];
				//支付总增值币				
				$cart_list [$key]['amount_coin'] = $v['goods_num'] * $v['coin_num'];
								
				$v ['shop_area_ids'] = unserialize($v ['shop_area_ids']) ; 

				unset($row);
				 //支付方式
				$row = shop_pay_type($v ['shop_area_ids'],$v);
				$cart_list [$key]['pay_name'] = $row ['pay_name'] ;
				$cart_list [$key]['m_html'] = $row ['m_html'] ;
				$cart_list [$key]['pay_id'] = $row["pay_id"] ;
						
				if ($storeid!==$v["store_id"]) {
					$storeid = $v["store_id"] ;
					$total[$v["store_id"]] += $cart_list [$key]['amount'] ;//商品金额
					$amount_points[$v["store_id"]] += $cart_list [$key]['amount_points'] ;//商品积分
					$amount_coin[$v["store_id"]] += $cart_list [$key]['amount_coin'] ;//增值币
				} else {
					$total[$v["store_id"]] += $cart_list [$key]['amount'];//商品金额
					$amount_points[$v["store_id"]] += $cart_list [$key]['amount_points'] ;//商品积分
					$amount_coin[$v["store_id"]] += $cart_list [$key]['amount_coin'] ;//增值币
				}	

				$v['goods_freight'] = floatval($v['goods_freight']);
				if (!$goods_freight[$v["store_id"]]) {
					$goods_freight[$v["store_id"]] = $v['goods_freight'] ;//物流运费
				}
				if ($v['goods_freight']>$goods_freight[$v["store_id"]]) {
					$goods_freight[$v["store_id"]] = $v['goods_freight'] ;//物流运费
				}									
				if (!$st_id) {
					$st_id = $v['store_id'] ;
					$i = $i + 1 ;
				}
				
				if ($st_id==$v['store_id']) {						
					$st_name = $v['store_name'];
					$st_state = $v['store_state'];							
				} else {
					unset($st_name);
					unset($st_state);
					unset($st_id);
					$st_id = $v['store_id'] ;
					$i = $i + 1 ;
					$st_name = $v['store_name'];
					$st_state = $v['store_state'];
				}
				$cart_st[$i-1]['store_name'] = $st_name ;
				$cart_st[$i-1]['store_state'] = $st_state ;
				$cart_st[$i-1]['store_id'] = $st_id ;
				
				$cart_st[$i-1]['son_c'][] = $cart_list [$key] ;
				
				$goods_freight2 += $goods_freight[$v["store_id"]] ;				
				$total2 += $total[$v["store_id"]] ;
				
				$pay_id = $cart_list [$key]['pay_id'] ;

				if ($storeid!==$v["store_id"]) {
					
					$storeid = $v["store_id"] ;
					//商品积分
					 $allpoints += $allpoints ;
					 //增值币
					 $allcoins += $allcoins ;
				 } else {
					//商品积分					 
					 $allpoints = $amount_points[$v["store_id"]] ;
					 //增值币
					 $allcoins = $amount_coin[$v["store_id"]] ;
				 } 
			}
			
			//dump($cart_st);die;	
			
			$alltotal = $goods_freight2 + $total2 ;//本店合计
			
			$result ['goods_freight'] = $goods_freight ;
			$result ['total'] = $total ;
			$result ['alltotal'] = $alltotal ;
			$result ['allpoints'] = $allpoints ;
			$result ['amount_points'] = $amount_points ;
			$result ['amount_coin'] = $amount_coin ;
			$result ['allcoins'] = $allcoins ;
			$result ['cart_st'] = $cart_st ;
			//最后一个为支付方式
			$result ['pay_id'] = $pay_id ;
				
			return $result ;
	 }
	 
	/**
	 * 立即购买单个产品信息
	 *
	 */	 
	 function buy_goods_list($goods_id, $goods_nums) {
		 
			$c_list = 'id=%d and goods_state=%d and goods_verify=%d' ;
			$c_arr = array($goods_id,1,1) ;
			$goods_bill = _getOne('product', $c_list, $c_arr) ;
			
			if ($goods_bill['goods_storage']<$goods_nums) {
				return 4;//库存不足
			}
			unset($str);
			unset($arr);
			$str = 'store_id=%d and store_state=%d' ;
			$arr = array($goods_bill['st_id'], 1);
			$goods_bill && $store = _getOne('store', $str, $arr) ;
						
			$result ['cart_st'][0]['store_name'] = $store ['store_name'] ;
			$result ['cart_st'][0]['store_id'] = $store ['store_id'] ;				
			$result ['cart_st'][0]['son_c'][0]['store_name'] = $store ['store_name'] ;
			$result ['cart_st'][0]['son_c'][0]['store_id'] = $store ['store_id'] ;
			$result['cart_st'][0]['son_c'][0]['goods_id'] = $goods_bill['id'] ;
			$result['cart_st'][0]['son_c'][0]['goods_num'] = $goods_nums ;
			$result['goods_num'] = $goods_nums ;
			$result['goods_id'] = $goods_id ;
			$result['cart_st'][0]['son_c'][0]['goods_image'] = $goods_bill['pic'] ;
			$result['cart_st'][0]['son_c'][0]['goods_name'] = $goods_bill['productname'] ;
			$result['cart_st'][0]['son_c'][0]['goods_price'] = $goods_bill['price'] ;
			
			$result['cart_st'][0]['son_c'][0]['point_num'] = $goods_bill['point_num'] ;
			$result['cart_st'][0]['son_c'][0]['coin_num'] = $goods_bill['coin_num'] ;
			$result['cart_st'][0]['son_c'][0]['give_coin'] = $goods_bill['give_coin'] ;
			
			//分区显示
			$goods_bill ['shop_area_ids'] = unserialize($goods_bill ['shop_area_ids']) ; 
			unset($row);
			 //支付方式
			$row = shop_pay_type($goods_bill ['shop_area_ids'], $goods_bill);
			$result['cart_st'][0]['son_c'][0]['pay_name'] = $row ['pay_name'] ;
			$result['cart_st'][0]['son_c'][0]['m_html'] = $row ['m_html'] ;
			$result['cart_st'][0]['son_c'][0]['pay_id'] = $row["pay_id"] ;
			$result['cart_st'][0]['son_c'][0]['pay_id'] = $row["pay_id"] ;
			$result['pay_id'] = $row ['pay_id'] ;						
		
			$result['cart_st'][0]['son_c'][0]['shop_area_ids'] = $goods_bill['shop_area_ids'] ;
						
			//商品运费
			$result ['goods_freight'][$goods_bill['st_id']] = floatval($goods_bill['goods_freight']);
			
			//商品总金额
			$result ['total'][$goods_bill['st_id']] = (intval($goods_nums) * floatval($goods_bill['price']));
			//商品总积分
			$result ['amount_points'][$goods_bill['st_id']] = (intval($goods_nums) * floatval($goods_bill['point_num'])) ;
			//总增值币
			$result ['amount_coin'][$goods_bill['st_id']] =(intval($goods_nums) * floatval($goods_bill['coin_num'])) ;
			
			//总金额
			$result ['alltotal'] = $result ['total'][$goods_bill['st_id']] + $goods_bill ['goods_freight'] ;
			//总积分	
			$result ['allpoints'] = $result ['amount_points'][$goods_bill['st_id']] ;
			//总增值币
			$result ['allcoins'] = $result ['amount_coin'][$goods_bill['st_id']] ;
			
			//商品金额	
			$result['cart_st'][0]['son_c'][0]['amount'] = $result ['total'][$goods_bill['st_id']] ;
			//商品积分
			$result['cart_st'][0]['son_c'][0]['amount_points'] = $result ['amount_points'][$goods_bill['st_id']] ;
			//商品增值币
			$result['cart_st'][0]['son_c'][0]['amount_coin'] = $result ['amount_coin'][$goods_bill['st_id']] ;
						
			return $result ;
	 }
	/**
	 * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
	 * 长度 =2位 + 10位 + 3位 + 3位  = 18位
	 * 1000个会员同一微秒提订单，重复机率为1/100
	 * @return string
	 */
	 function makePaySn($member_id) {
		return mt_rand(10,99)
		      . sprintf('%010d',time() - 946656000)
		      . sprintf('%03d', (float) microtime() * 1000)
		      . sprintf('%03d', (int) $member_id % 1000);
	}
	/**
	 * 订单编号生成规则，n(n>=1)个订单表对应一个支付表，
	 * 生成订单编号(年取1位 + $pay_id取13位 + 第N个子订单取2位)
	 * 1000个会员同一微秒提订单，重复机率为1/100
	 * @param $pay_id 支付表自增ID
	 * @return string
	 */
	function makeOrderSn($pay_id) {
	    //记录生成子订单的个数，如果生成多个子订单，该值会累加
	    static $num;
	    if (empty($num)) {
	        $num = 1;
	    } else {
	        $num ++;
	    }
		return (date('y',time()) % 9+1) . sprintf('%013d', $pay_id) . sprintf('%02d', $num);
	}

	/**
	 * 添加订单支付数据
	 *
	 *
	 */
	 function AddPay_sn($table, $pay_sn, $state) {
		if ($pay_sn) {
			$data ['pay_sn'] = $pay_sn ;
			$data ['api_pay_state'] = 0 ;
			$data ['buyer_id'] = $_SESSION['user_id'] ;
			$result = _getAdd($table, $data);
		}
		return $result ;
	 }

	/**
	 * 添加订单
	 *
	 *
	 */
	 function _addOrder($table, $data) {
		if ($data) {			
			$result = _getAdd($table, $data);
		}
		return $result ;
	 }	 
	
	/**
	 * 更新库存与销量
	 *
	 * @param array $buy_items 商品ID => 购买数量
	 */
	 function editGoodsNum($buy_items) {
		  //更新库存与销量 和 店铺销量					
		  $i = 0 ;
					
		  foreach ($buy_items as $key => $v) {					

					//更新库存
					unset($str);
					unset($arr);
					unset($cache);
					unset($data);
					$cache = 'goods'.$v['goods_id'] ;
					$str = "id=%d" ;					
					$arr = array($v['goods_id']) ;
					$k = 0;
					//规格更新库存
					$data = array();
					$goods = array();
					$spec_arr = array();
					
					$goods = _getOne('product', $str, $arr) ;
					$spec_arr = unserialize($goods ['goods_spec_arr']);
					
					if ($v['colorkey'] && $v['speckey']) {

						$k = $v['colorkey'].'|'.$v['speckey'] ;
						foreach ($spec_arr as $kk=>$vv) {
							$spec_arr [$kk] = $vv ;
							if ($kk===$k) {
								$spec_arr [$kk]['stock'] = $vv['stock'] - $v ['goods_num'] ;
							}							
						}
						$data ['goods_spec_arr'] =  serialize($spec_arr) ; 
					}
					$data ['goods_salenum'] =  $v ['goods_salenum'] + $v ['goods_num'] ;
					$data ['goods_storage'] =  $goods ['goods_storage'] - $v ['goods_num'] ;
					
					_getEdit('product',$str, $arr , $data, $cache) ;
					//更新销量
					unset($str);
					unset($arr);
					unset($data);
					$str = "store_id=%d" ;
					$arr = array($v['store_id']) ;
					$store_one = _getOne('store', $str, $arr) ;						
					$data ['store_sales'] =  $store_one ['goods_storage'] + $v ['goods_num'] ;
								
					$st_sales = _getEdit('store',$str, $arr , $data) ;	
					$i++;
			}
			
			return $st_sales ;
	 }

	 
	/*
	*在线支付状态更新
	*
	*/
	function payOrder2 ($pay_sn) {
		//第三方支付更新支付状态
		unset($str);
		unset($arr);
		unset($data);
		$str = "pay_sn='%s'";
		$arr = array($pay_sn);
		$data ['api_pay_state'] =  1 ;
		$order_st = _getEdit('order_pay',$str, $arr , $data) ;		
	}
	
	/*
	*返回值：如果订单已经成功支付，
	*返回true，否则返回false；
	*/	
	function checkorderstatus($ordid){

		unset($str);
		unset($arr);
		$str = "order_sn='%s'" ;
		$arr = array($ordid) ;
		$ordstatus = _getOne('order', $str, $arr) ;
		if($ordstatus['order_state']==='10'){
			return true;
		}else{
			return false;    
		}
	 }	
	 
	/*
	*处理订单函数
	*更新订单状态，写入订单支付后返回的数据
	*/	 
	 function orderhandle($table, $parameter, $res){
		$cache = 'user_'.$_SESSION['user_id'];
		$userinfo = S($cache);		
		$order_list = $_SESSION['order_list_onlie'] ; 
		
		$pay_user = pay_order_in($_SESSION['paymoney_www'],  $_SESSION['paypoints'], $userinfo, $res, $order_list) ;

		session('res_pay',null);
		//站内支付金额
		$pd_amount =  0 ;
		if ($_SESSION['paymoney_www']>0) {			
			$pd_amount = $_SESSION['paymoney_www'] ;			
		} 
		
		if ($_SESSION['paymoney_online']>0) {
			//在线支付金额
			$data['online_amount']  = $_SESSION['paymoney_online'] ; 
			//在线支付代码
			$data['online_pay_code']  = $_SESSION['online_pay_type'] ; 
		}
		
		//在线支付状态更新
		$pay_num2 = payOrder2($order_list['pay_sn']) ;
		
		$pay_sn = $parameter['out_trade_no'];//订单编号
		
		$data['order_state']  = 20 ; //支付状态
		$data ['finnshed_time'] =  time() ;
		$data['pd_amount']  = $pd_amount ; //预存款支付金额
		if ($_SESSION['online_pay_type']) {
			$parameter['trade_no'] && $data['trade_no']      = $parameter['trade_no'];//支付宝交易号；
			$parameter['notify_id'] && $data['notify_id']     = $parameter['notify_id'];//通知校验ID。
			$parameter['buyer_email'] && $data['buyer_email']   = $parameter['buyer_email'];//买家支付宝帐号	
			
		}
		
		$result = payOrderAll($table, $pay_sn, $data) ;
		unset($data);
	 } 
	 
	/*
	*更新订单支付状态
	* pd_amount 预存款支付金额
	*/
	function payOrderAll($table, $pay_sn, $data) {
		//更新订单支付状态
		$str = "order_sn='%s'";
		$arr = array($pay_sn);					
		$order_st = _getEdit($table,$str, $arr , $data) ;
		
		$cache = 'user_'.$_SESSION['user_id'];
		session('online_pay_type',null);
		session('paymoney_www',null);
		session('paymoney_online',null);
		session('order_list_onlie',null);
		session('paypoints',null);
		
		S($cache,null);	
		
		return $order_st ;
	}	
	
	/*
	* 获取分区
	*/
	 function shop_area_str($gid) {
			
			$result = M('shop_area') -> where('shop_area_id = %d',$gid)->field('shop_area_name,pay_id')->find();
			if ($result) {
				$row = M('payment') -> where('payment_id=%d and payment_state=%d',array($result['pay_id'],1))->field('payment_code,payment_id,payment_name,payment_state')->find();
				if (!$row) {
					return 0;
				}
				$data = array() ;
				$data['shop_area_name'] = $result['shop_area_name'] ;
				$data['payment_code'] = $row['payment_code'] ;
				$data['payment_name'] = $row['payment_name'] ;
				$data['pay_id'] = $result['pay_id'] ;
				return $data;
			} else {
				return 10;		
			}		
	}
	
	/*
	*站内支付扣除金额
	*/
	function pay_order_money($table, $type, $money, $id){

		unset($str);
		unset($arr);
		$str = $id."=%d";
		$arr = array($_SESSION['user_id']);
		
		if ($type && $money) {
			$pay_user = M($table)->where($str, $arr)->setDec($type,$money); 
		}
		
		return $pay_user ;
	 }	
	
	/*
	* 消费积分支付
	*
	* 不需要在线支付  integral1 静态积分 + integral2 动态帐户 + integral5 消费帐户
	*
	*/
	function pay_points($table, $money, $UserInfo){
		
		$pay_user = 0 ;
		
		if (!$UserInfo) {
			return 0 ;
		}
		unset($str);
		unset($arr);
		$str = "userid=%d";
		$arr = array($_SESSION['user_id']);
		$type[0] = 'integral1' ;//静态积分
		$type[1] = 'integral2' ;//动态帐户
		$type[2] = 'integral5' ;//消费帐户
		$id = 'userid' ;
		
		$state = 0 ;
		$last_amount = 0 ;
		
		if ($type && $money) {
			for ($i=0;$i<3;$i++) {
				
				unset($pay_user);
				if ($UserInfo[$type[$i]]>0 && !$last_amount) {
					$last_amount = $money - $UserInfo[$type[$i]] ;
					$pay_user = pay_order_money($table, $type[$i], $money, $id) ;
					$state = $state + 1 ;
				}
				
				if ($last_amount>0) {
					//剩余支付积分数
					$money = $last_amount ;
					$last_amount = 0 ;				
				}
			}
			
		}
		
		return $state ;
	 }

	/*
	* 预存款支付
	*
	* member_balance
	*
	*/
	function pay_balance($table, $money, $UserInfo){
		
		$pay_user = array() ;
		
		if (!$UserInfo) {
			return 0 ;
		}
		unset($str);
		unset($arr);
		$str = "id=%d";
		$arr = array($_SESSION['user_id']);
		$type = "member_balance" ;
		$id = 'id' ;
		
		//余额不足时
		if ($UserInfo['member_balance']<$money) {			
			//需要在线支付的金额
			$pay_user[1] = $money - $UserInfo['member_balance'] ;
			$money = $UserInfo['member_balance'] ;
		} else {
			$pay_user[1] = 0 ;
		}
		
		$pay_user[0] = pay_order_money($table, $type, $money, $id) ;
		
		 return $pay_user ;
	 }		 
	
	/*
	* 增值币支付
	* 	
	* gold_coin
	*
	*/
	function pay_gold_coin($table, $money, $UserInfo){
		
		$pay_user = 0 ;
		
		if (!$UserInfo) {
			return 0 ;
		}
		unset($str);
		unset($arr);
		$str = "id=%d";
		$arr = array($_SESSION['user_id']);
		$type = "gold_coin" ;
		$id = 'id' ;
				
		$pay_user = pay_order_money($table, $type, $money, $id) ;
		
		return $pay_user ;
	 }
	 
	/*
	* 站内支付订单
	* 	
	*
	*/
	function pay_order_in($money, $paypoints, $UserInfo, $res, $order_list){

		switch ($res) {
			
			case 1:
			//预存款支付
			$table = "user" ;
			$pay_user = pay_balance($table, $money, $UserInfo);
			break;
			
			case 2:
			//积分支付
			$table = "integral" ;
			$pay_user = pay_points($table, $paypoints, $UserInfo) ;
			break;
			
			case 3:
			//积分支付
			$table = "integral" ;
			$pay_points = pay_points($table, $paypoints, $UserInfo) ;
			//预存款支付
			$table = "user" ;
			$pay_user = pay_balance($table, $money, $UserInfo);
			break;		
			
			case 4:
			//增值币支付
			$table = "user" ;
			$pay_user = pay_gold_coin($table, $money, $UserInfo) ;
			break;
		}
		
		//更新库存与销量
		if ($pay_user) {
			unset($i);
			$i = editGoodsNum($order_list['goods_list']);
			$cache = 'user_'.$_SESSION['user_id'];
			S($cache,null);				
			return 1 ;
		} else {
			return 0 ;
		}
	 }
	 
	/*
	* 赠送增值币
	* 	
	*
	*/
	function give_gold_coin($order_list){
		unset($str);
		unset($arr);
		$str = "order_id=%d" ;
		$arr = array($order_list['order_id']) ;		
		$order_goods = M('order_goods')->where($str, $arr)->field('goods_id')->select();
		foreach ($order_goods as $key=>$v) {
			if ($v['give_coin']>0) {
				unset($str);
				unset($arr);
				$str = "id=%d" ;
				$arr = array($_SESSION['user_id']) ;
				M('user')->where($str, $arr)->setInc('gold_coin',$v['give_coin']);
			}			
		}		
	 }
	 
	/*
	* 支付方式2
	* 	
	*
	*/
	function shop_pay_type($area_id,$goods){
					
			if ($area_id['payment_code']) {
				$pay_type = _getOne('payment', 'payment_code="%s"', array($area_id['payment_code'])) ;
				$goods['price'] = $goods['order_amount'] ;//现金
				$goods['coin_num'] = $goods['gold_amount'] ;//增值币
				$goods['point_num'] = $goods['points_amount'] ;//积分
				$result["payment_name"] = $pay_type ["payment_name"] ;//支付方式
				$result["payment_code"] = $pay_type ["payment_code"] ;//支付方式
				$result["pay_id"] = $pay_type ["payment_id"] ;
			} else {
				$pay_type = shop_area_str($area_id);
				$result["pay_id"] = $pay_type ["pay_id"] ;
			}
			//dump($pay_type);die;
			if (!$goods['price']) {
				$goods['price'] = $goods['goods_price'] ;
			}
			if (!$goods['goods_price'] && !$goods['price']) {
				$goods['price'] = $goods['goods_pay_price'] ;
			}
			
			if ($pay_type["payment_code"]==="points_consume") {
				
				$result['pay_name'] = "现金&nbsp;+&nbsp;积分";
				$result['m_html'] = '¥'.$goods['price'].'&nbsp;+&nbsp;'.$goods['point_num'].'<font style="font-size:17px;">积分</font>';
				$result["unit"] = "&nbsp;积分" ;
				
			} else if ($pay_type["payment_code"]==="points") {
				
				$result['pay_name'] = "积&nbsp;&nbsp;分&nbsp;&nbsp;价&nbsp;";
				$result['m_html'] = $goods['point_num'].'<font style="font-size:17px;">积分</font>';
				$result["unit"] = "&nbsp;积分" ;
			
			} else if ($pay_type["payment_code"]==="consume") {
				
				$result['pay_name'] = "商&nbsp;&nbsp;城&nbsp;&nbsp;价";
				$result['m_html'] = '¥'.$goods['price'].'';
				$result["unit"] = "" ;
				
			} else if ($pay_type["payment_code"]==="coinpay") {
				
				$result['pay_name'] = "增&nbsp;&nbsp;值&nbsp;&nbsp;币";
				$result['m_html'] = $goods['coin_num'].'&nbsp;币';
				$result["unit"] = "&nbsp;币" ;
			}
			
			//dump($goods['price']);die;
			return $result;
	 }

	/*
	* 图片压缩
	* 	
	*
	*/
	function thumb_img($img, $name, $type , $goods, $w=150 ,$h=150){
		
		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg
		if (!$goods['createtime']) {
			$riqi = date("Y-m-d",time());
		} else {
			$riqi = date("Y-m-d",$goods['createtime']);
		}
		if ($goods['id']) {
			$g_id = $goods['id'] ;
		} else {
			$g_id = time() ;
		}
		
		if ($type==1) {
			$name = './Public/upload/thumb/shop/'.$name.$g_id.".jpg";
		} else if ($type==2) {
			if ($goods['st_id']) {
				
				$url = './Public/upload/thumb/store/';			
				@mkdir('./Public/upload/thumb/',777,true);
				@mkdir($url,777,true);
				@chmod($url, 0777);
				
				$path = $url.$goods['st_id'] ;
				@mkdir($path,0777,true);
				@chmod($path, 0777);
				//dump(mkdir($path));die;
				if (!file_exists($path)){
					define($path, __DIR__);
					mkdir($path); 
				}
				
				$path2 = $url.$goods['st_id'].'/'.$riqi;
				@mkdir($path2,777,true);
				@chmod($path2, 0777);				
				if (!file_exists($path2)) {

					mkdir($path2); 
				}
				
				$name = $path2.'/'.$name.$g_id.".jpg";
			}
		}
		
		if (file_exists('.'.$img)) {
			
			if (!file_exists($name)) {
				
				$image = new \Think\Image(); 

				$image->open('.'.$img);
				//$name = './Public/upload/store/thumb/123456.jpg';

				$pic = $image->thumb($w, $h)->save($name,'jpg');
				//dump($pic);exit;
				if ($pic===$name) {
					$pic = $pic ;
				} else {
					$pic = $name ;
				}
								
			} else {
				$pic = $name ;
			}
			
			return substr($pic,1) ;			
		}

	 }	


	/*
	 *加载缓存
	 */
	function oncache($type, $table){
		switch ($type) {
			case 'adv':
				$str = 'adv_id>%d and adv_type=%d' ;
				$data= array(0,2) ;	
				$list = M($table)->where($str, $data)->select();
				foreach ($list as $key => $v) {
					unset($cache);
					$cache = 'home_adv_'.$v['ap_id'] ;
					if (!S($cache)) {
						S($cache,$v);
					}				
				}
				
			break;
		}
	 }

	/*
	 *删除图片
	 */
	function del_img($img){
		$del = unlink($img);
		return  $del ;
	 }


	 
	